'use strict';
const db = uniCloud.database();
const tablename = "bbs-topic";
const dbCmd = db.command
exports.main = async (event, context) => {
	let params = event.params
	const action = event.cloudAction || event.action;
	let userid = params.bloggerId;
	switch (action) {
		case "my":
			var collection = db.collection("love")
			var row = await collection.where({
					userid: userid,
					tablename: tablename
				})
				.orderBy("_id", "desc")
				.skip(params.start)
				.limit(params.limit)
				.get();
			if (row.data.length > 0) {
				var ids = [];
				for (var i in row.data) {
					ids.push(row.data[i].objectid);
				}
				var res = await uniCloud.callFunction({
					name: "bbs_topic",
					data: {
						cloudAction: "getListByIds",
						params: {
							ids: ids
						}
					}
				})
				return {
					error: 0,
					data: {
						list: res.result.data
					}
				}
			} else {
				return {
					error: 0,
					data: {
						list: []
					}
				}
			}
			return event
			break;
		case "getmyfabulous":
			var collection = db.collection("bbs-topic")
			var res = await collection.aggregate()
				.match({
					uid: dbCmd.eq(params.bloggerId)
				})
				.end()
			var total = 0
			for (var i = 0; i < res.data.length; i++) {
				if (res.data[i].love_num) {
					total += Number(res.data[i].love_num)
				}
			}
			return total;
			break;
		case "getmyfabulousList":
			var collection = db.collection("bbs-topic")
			var res = await collection.aggregate()
				.match({
					uid: dbCmd.eq(userid)
				})
				.end()
			var list = []
			for (var i = 0; i < res.data.length; i++) {
				var row = await db.collection("love").aggregate()
					.match({
						objectid: dbCmd.eq(res.data[i]._id)
					})
					.lookup({
						from: 'uni-id-users',
						localField: 'userid',
						foreignField: '_id',
						as: 'userInfo',
					})
					.end()
				for (var a = 0; a < row.data.length; a++) {
					if (row.data[a].userInfo) {
						list.push(row.data[a].userInfo[0])
					}
				}
			}
			return list;
			break;
	}
};
